from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

def debug_baidu():
    print("=== 调试百度页面结构 ===")
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--window-size=1920,1080')
    
    driver = None
    try:
        # 使用webdriver-manager自动管理ChromeDriver
        print("正在自动下载和配置ChromeDriver...")
        service = Service(ChromeDriverManager().install())
        print("ChromeDriver准备就绪")
        
        # 启动浏览器
        print("正在启动浏览器...")
        driver = webdriver.Chrome(service=service, options=chrome_options)
        print("浏览器已启动")
        
        # 访问百度首页
        print("正在访问百度首页...")
        driver.get("https://www.baidu.com")
        print("已访问百度首页")
        
        # 等待页面加载
        time.sleep(3)
        
        # 打印页面标题
        print(f"页面标题: {driver.title}")
        
        # 打印页面URL
        print(f"页面URL: {driver.current_url}")
        
        # 获取页面源码
        print("页面源码预览（前1000字符）:")
        source = driver.page_source
        print(source[:1000])
        
        # 尝试查找常见的搜索框ID
        common_ids = ["kw", "input", "search", "query", "search-input"]
        for id_name in common_ids:
            try:
                element = driver.find_element("id", id_name)
                print(f"找到ID为 '{id_name}' 的元素: {element.tag_name}")
            except:
                print(f"未找到ID为 '{id_name}' 的元素")
        
        # 尝试通过其他方式查找搜索框
        try:
            elements = driver.find_elements("tag name", "input")
            print(f"找到 {len(elements)} 个 input 元素:")
            for i, element in enumerate(elements[:10]):
                placeholder = element.get_attribute("placeholder")
                name = element.get_attribute("name")
                id_attr = element.get_attribute("id")
                print(f"  {i+1}. ID: {id_attr}, Name: {name}, Placeholder: {placeholder}")
        except Exception as e:
            print(f"查找input元素时出错: {e}")
            
    except Exception as e:
        print(f"调试过程中发生错误: {e}")
    finally:
        if driver:
            try:
                driver.quit()
                print("浏览器已关闭")
            except:
                print("关闭浏览器时出错")

if __name__ == "__main__":
    debug_baidu()